import sys
from uuid import uuid4
from json import dumps, loads
from httplib import HTTPConnection
from handlers import get_filename

#######################################################################
# This file is an example of how to use the WWW API for Mediadart
#######################################################################

#PORT=8081    # when using twisted_server.py
PORT=8080    # when using cherry_server.py

#
# Utility function to build valid json requests
#
def json_request(request_id, method, params, callback_url=''):
    request = { 'method': method, 'params': params, 'id': request_id, 'callback_url': callback_url,}
    try:
        data = dumps(request)
    except Exception, e:
        print 'Json error: %s' % str(e)
        raise
    return data

#
# Example on how to send a synchronous request
#
def doBlockingRequest(request_id, server, method, params):
    request_id = uuid4().get_hex()[:8]
    responsefile = get_filename('.', request_id)
    req = json_request(request_id, method, params)
    conn = HTTPConnection('localhost', 8081) 
    conn.request('POST', '/webproxy/%s' % server, req)
    resp_data = conn.getresponse()
    f = open(responsefile, 'w')
    f.write(resp_data.read())
    f.close()
    print 'Request %s: received %s-%s: response in %s' % (request_id, resp_data.status, resp_data.reason, responsefile)


def doNonBlockingRequest(request_id, server, method, params, callback_url):
    req = json_request(request_id, method, params, callback_url)
    conn = HTTPConnection('localhost', 8081) 
    conn.request('POST', '/webproxy/%s' % server, req)
    resp_data = conn.getresponse()
    print 'Request %s: received %s-%s:' % (request_id, resp_data.status, resp_data.reason)


if __name__=='__main__':    
    # a request that blocks, with no updates
    request_id = uuid4().get_hex()[:4]
    #doBlockingRequest(request_id, 'FooServer', product', [7, 4])
    #doBlockingRequest(request_id, 'Crawler', 'crawl', [['cat', 'dog']])

    # a request that does not block, with no updates, response written in '.'
    request_id = uuid4().get_hex()[:4]
    #doNonBlockingRequest(request_id, FooServer', 'product', [7, 4], 'http://localhost:%s/reply/' % PORT)
    doNonBlockingRequest(request_id, 'Crawler', 'crawl', [['cat', 'dog']], 'http://localhost:%s/reply/' % PORT)

    # a request that does not block, with no updates, response written in '/tmp'
    request_id = uuid4().get_hex()[:4]
    #doNonBlockingRequest(request_id, FooServer', 'product', [7, 4], 'http://localhost:%s/reply2/' % PORT)

    # a request that does not block, with updates
    request_id = uuid4().get_hex()[:4]
    #doNonBlockingRequest(request_id, FooServer', 'updating_product', 
    #                     [7, 4, 'http://localhost:%s/updates/%s' % (PORT, request_id)], 
    #                     'http://localhost:%s/reply/' % PORT)
